﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using QuanLyThongTinCoSo.Biz;
using QuanLyThongTinCoSo.Common;
using QuanLyThongTinCoSo.Entity;
using QuanLyThongTinCoSo.Model;

namespace QuanLyThongTinCoSo.Forms.Settings
{
    public partial class ViewUser : Form
    {
        public ViewUser()
        {
            InitializeComponent();
        }

        private void SetPreferences()
        {
            grvUsers.AutoGenerateColumns = false;
        }

        private void BuildData(Entities context)
        {
            var biz = new UserBiz(context);
            grvUsers.DataSource = null;
            grvUsers.Refresh();
            grvUsers.DataSource = biz.GetAll();
        }

        private void FormLoad(object sender, EventArgs e)
        {
            var parent = MdiParent as MDI;
            if (parent != null)
            {
                parent.Status.Text = string.Empty;
            }

            var context = new Entities();

            SetPreferences();
            BuildData(context);
        }
        
        private void NewUser(object sender, EventArgs e)
        {
            Utilities.CloseForm(this, new NewUser());
        }

        private void UpdateUser(object sender, EventArgs e)
        {
            if(grvUsers.SelectedRows.Count > 0)
            {
                MessageBox.Show(Constants.Messages.UpdateMultipleItemsMessage);
            }
            else
            {
                var selectedRow = grvUsers.CurrentRow;
                if (selectedRow != null)
                {
                    var id = (int)selectedRow.Cells[3].Value;

                    var editForm = new NewUser(id);
                    Utilities.CloseForm(this, editForm);
                }
            }
        }

        private void DeleteUsers(object sender, EventArgs e)
        {
            var result = MessageBox.Show(this, Constants.Messages.DeleteConfirm, string.Empty, MessageBoxButtons.YesNo);

            if(result == DialogResult.Yes)
            {
                var context = new Entities();
                var userBiz = new UserBiz(context);

                var deletedUsers = new List<BaseModel>();

                foreach (DataGridViewRow selectedRow in grvUsers.SelectedRows)
                {
                    var user = selectedRow.DataBoundItem as User;
                    deletedUsers.Add(new User
                    {
                        Id = user.Id
                    });
                }

                userBiz.DeleteItems(deletedUsers);

                BuildData(context);
            }
        }
    }
}
